package com.yyq.adms.sysmanage.action;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.yyq.adms.sysmanage.bpo.SysModulesBpo;
import com.yyq.adms.sysmanage.pojo.DataDictionary;
import com.yyq.adms.sysmanage.pojo.SysModules;
import com.yyq.adms.usermanage.pojo.SysModulePerms;
import com.yyq.adms.usermanage.pojo.SysPerm;
import com.yyq.adms.usermanage.pojo.SysRPM;
import com.yyq.adms.usermanage.pojo.SysUsersRoles;
import com.yyq.sos.action.BaseAction;
import com.yyq.sos.constants.ActionType;
import com.yyq.sos.constants.Constants;
import com.yyq.sos.permission.LoginUser;
import com.yyq.sos.util.DepartmentUtil;
import com.yyq.sos.util.PlateFormUtil;
import com.yyq.sos.util.SysModulesUtil;

@Controller("sysModulesAction")
@Scope("prototype")
public class SysModulesAction extends BaseAction 
{
	private static final long serialVersionUID = 5531541120927266266L;
	SysModules po = new SysModules();
	private SysModulesBpo bpo ;
	
	@Resource(name="sysModulesBpo")
	public void setBpo(SysModulesBpo bpo) {
		bpo.setCls(po.getClass());
		this.bpo = bpo;
	}

	public String execute()throws Exception
	{
		super.setBpo(bpo);
		super.setObj(po);
		String s = super.execute();
		this.setPo((SysModules)super.getObj());
		return s;
	}
	
	public String goUpdate() {
		String s = super.goUpdate();
		if(this.getFormValue("type")==null)
			return s;
		else{
			this.setFormValue("formMap.mps", bpo.search("from "+SysModulePerms.class.getName()+" o where o.moduleId="+po.getId()));
			this.setFormValue("formMap.perms", bpo.search("from "+SysPerm.class.getName()));
			return "goPerm";
		}
	}

	public String update() {
		if(this.getFormValue("type")==null){
			String ret = super.update();
			SysModulesUtil.getInstance().rebuildMap();
			return ret;
		}else{
			boolean flag = bpo.exist("from "+SysModulePerms.class.getName()+" o where o.moduleId="+po.getId());
			boolean issuccess = false;
			if(flag){
				if(bpo.execHql("delete "+SysModulePerms.class.getName()+" o where o.moduleId="+po.getId())){
					issuccess = true;
				}
			}else {
				issuccess = true;
			}
			if(issuccess){
				String[] s = (String[])this.getFormValue("perms");
				List perms = bpo.search("from "+SysPerm.class.getName()+" where permName='READ'");
				SysPerm read = (SysPerm)perms.get(0);
				List list = new ArrayList();
				boolean exist=false;
				if (s!=null){
					for(int i=0,len=s.length ;i<len;++i){
						SysModulePerms smp = new SysModulePerms();
						smp.setModuleId(po.getId());
						smp.setPermId(new Long(s[i]));
						list.add(smp);
						if(s[i].equals(String.valueOf(read.getId())))
							exist = true;
					}
					if(!exist){
						SysModulePerms smp = new SysModulePerms();
						smp.setModuleId(po.getId());
						smp.setPermId(read.getId());
						list.add(smp);
					}
					bpo.save(list.toArray());
				}
				this.setMsg("{processId:\"1\",msg:\"更新操作集合成功\"}");
			}else{
				this.setMsg("{processId:\"-1\",msg:\"更新操作集合失败\"}");
			}
			return ActionType.ACTION_MSG;
		}
	}

	public String delete()
	{
		Object ids = this.getFormValue("ids");
		if(ids!=null && ((String[])ids).length>0){
			String[] id = (String[])ids;
			String sql = "delete "+SysModules.class.getName()+" where ";
			for(int i=0; i<id.length; ++i){
				sql += " parentId = "+id[i]+"   or";
			}
			sql = sql.substring(0, sql.length()-3);
			bpo.delete(sql);
		}
		String ret = super.delete();
		SysModulesUtil.getInstance().rebuildMap();
		return ret;
	}
	
	public String add()
	{
		String level = (String)bpo.max("moduleLevel", "parentId="+po.getParentId());
		if(level != null && level.length()==2)
			level = String.valueOf(Long.parseLong(level)+1);
		else if(level!=null && level.length()==4)
			level = String.valueOf(Long.parseLong(level)+1);
		else if(level==null && po.getParentId().longValue()==0)
			level = "10";
		else if(level==null && po.getParentId().longValue()!=0)
		{
			SysModules obj = (SysModules)bpo.findByPk(po.getParentId());
			level = obj.getModuleLevel()+"10";
		}
		po.setModuleLevel(level);
		super.add();
		this.setPo((SysModules)super.getObj());
		String perms = (String)this.getRequest().getSession().getServletContext().getAttribute("permission");
		if(perms!=null && perms.toUpperCase().equals("TRUE")){
			String url = po.getModuleUrl();
			if(url.indexOf("?")>0)
				url = url.substring(0,url.indexOf("?"));
			//PermissionFilter.list.add(url);
		}
		SysModulesUtil.getInstance().rebuildMap();
		return ActionType.ACTION_MSG;
	}
	
	@Override
	public String goTree() {
		String tree = bpo.getTree();
System.out.println(tree);
		PrintWriter out = null;
		try {
			HttpServletResponse rs = this.getResponse();
			rs.setCharacterEncoding("UTF-8");
			rs.setContentType("application/json");
			out = rs.getWriter();
			out.write(tree);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(out != null){
				out.close();
			}
		}
		
		return null;
	}
	
	public String search()
	{
		LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		String sql = "select DISTINCT m.id,m.module_cname,m.module_url,m.parent_id from ss_sys_modules m" +
		" join ss_sys_role_perm_module rpm on m.id=rpm.module_id " +
		" join ss_sys_users_roles ur on rpm.role_id=ur.role_id" +
		" where m.parent_id=(select parent_id from ss_sys_modules  where id="+po.getId()+")"+
		" and m.sts='ACTV' and m.module_name<>'CommonLink' and m.is_menu=1 and ur.user_id="+user.getUserId();
		String moduleName = SysModulesUtil.getInstance().getModuleName(po.getId());
		
		if(isGlobalPermissions(moduleName)){
			sql = "select id,module_cname,module_url,parent_id from ss_sys_modules where parent_id=(select parent_id from ss_sys_modules where id="+po.getId()+")"+
			" and sts='ACTV' and module_name<>'CommonLink' and is_menu=1";
		}
		
		List modules = bpo.searchSql(sql);
		List mods = new ArrayList();
		long m1pid = 0;
		for(int i=0;i<modules.size();i++){
			Object[] objs = (Object[])modules.get(i);
			SysModules m = new SysModules();
			m.setId(Long.parseLong(objs[0].toString()));
			m.setModuleCname(objs[1].toString().replaceAll("\\s", ""));
			m.setModuleUrl(objs[2].toString());
			m.setParentId(Long.parseLong(objs[3].toString()));
			if(i==0){
				m1pid = m.getParentId();
			}
			mods.add(m);
		}
		this.setFormValue("tableNameSel", mods);
		sql = "select DISTINCT m.id,m.module_cname,m.module_url,m.parent_id from ss_sys_modules m" +
		" join ss_sys_role_perm_module rpm on m.id=rpm.module_id " +
		" join ss_sys_users_roles ur on rpm.role_id=ur.role_id" +
		" where m.parent_id=(select parent_id from ss_sys_modules  where id="+m1pid+")"+
		" and m.sts='ACTV' and m.module_name<>'CommonLink' and m.is_menu=1 and ur.user_id="+user.getUserId();
		if(isGlobalPermissions(moduleName)){
			sql = "select id,module_cname,module_url,parent_id from ss_sys_modules where parent_id=(select parent_id from ss_sys_modules where id="+m1pid+")"+
			" and sts='ACTV' and module_name<>'CommonLink' and is_menu=1";
		}
		modules = bpo.searchSql(sql);
		mods = new ArrayList();
		long m2pid = 0;
		for(int i=0;i<modules.size();i++){
			Object[] objs = (Object[])modules.get(i);
			SysModules m = new SysModules();
			m.setId(Long.parseLong(objs[0].toString()));
			m.setModuleCname(objs[1].toString().replaceAll("\\s", ""));
			m.setModuleUrl(objs[2].toString());
			m.setParentId(Long.parseLong(objs[3].toString()));
			if(i==0){
				m2pid = m.getParentId();
			}
			mods.add(m);
		}
		
		List searchPropertyList = bpo.search("from DataDictionary where parentId="+po.getId());
		if(isGlobalPermissions(moduleName)){
			DataDictionary dd = new DataDictionary();
			dd.setParentId(po.getId());
			dd.setText("报送单位");
			dd.setValue("sentDep");
			searchPropertyList.add(dd);
		}
		
		this.setFormValue("childTypeSel", mods);
		this.setFormValue("searchPropertySel", searchPropertyList);
		this.setFormValue("typeSelId", m2pid);
		this.setFormValue("childTypeSelId", m1pid);
		return ActionType.ACTION_SEARCH;
	}
	
	public String data()
	{
		String sql = "from "+SysModules.class.getName()+" where parentId="+po.getParentId();
		
		this.setFormData(bpo.searchPage(sql,this.getPageForm().getPageNo(), this.getPageForm().getPageSize()));
		return ActionType.ACTION_DATA_LIST;
	}
	
	public String menu()
	{
		LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		String tree = bpo.getMenuByGroup(String.valueOf(user.getUserId()));
		System.out.println(tree);
		PrintWriter out = null;
		try {
			HttpServletResponse rs = this.getResponse();
			rs.setCharacterEncoding("UTF-8");
			rs.setContentType("application/json");
			out = rs.getWriter();
			out.write(tree);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(out != null){
				out.close();
			}
		}
		
		return null;
	}

	public SysModules getPo() {
		return po;
	}

	public void setPo(SysModules po) {
		this.po = po;
	}

	public String change(){
		String changeFlag = ((String[])this.getFormValue("changeFlag"))[0];
		String modulesId = ((String[])this.getFormValue("modulesId"))[0];
		List list = null;
		String moduleName = null;
		
		if("sentDep".equals(modulesId)){
			list = DepartmentUtil.getInstance().getSentDeps();
			this.setFormValue("selData", list);
			return ActionType.ACTION_CHANGE;
		}else if("belongPlateFormID".equals(modulesId)){
			list = PlateFormUtil.getInstances().getPlateForms();
			this.setFormValue("selData", list);
			return ActionType.ACTION_CHANGE;
		}
		if(!changeFlag.equals("searchPropertySel")){
			long modulesIdLong = 0;
			try {
				modulesIdLong = Long.parseLong(modulesId);
			} catch (NumberFormatException e) {
			}
			if(modulesIdLong != 0)
			moduleName = SysModulesUtil.getInstance().getModuleName(modulesIdLong);
		}
		if(changeFlag.equals("tableNameSel")){
			list = bpo.search("from DataDictionary where parentId="+modulesId);
			if(isGlobalPermissions(moduleName)){
				DataDictionary dd = new DataDictionary();
				dd.setParentId(Long.parseLong(modulesId));
				dd.setText("报送单位");
				dd.setValue("sentDep");
				list.add(dd);
			}
			
		}else if(changeFlag.equals("searchPropertySel")){
			list = bpo.search("from DataDictionary where key='"+modulesId+"'");
		}else{
			LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
			String sql = "";
			String condition = " and obj.id not in(325,326,328) ";
			if(user.getOrgId().intValue() == 14){
				condition = "";
			}
			if(this.isGlobalPermissions(moduleName)){
				sql = "from SysModules obj where obj.moduleName<>'CommonLink' and obj.sts='ACTV' and obj.isMenu=1 and obj.parentId="+modulesId+condition;
			}else{
				sql =  "select distinct obj from "
					+ SysModules.class.getName()
					+ " obj,"
					+ SysUsersRoles.class.getName()
					+ " objUR,"
					+ SysRPM.class.getName()
					+ " objRPM "
					+ " where  obj.moduleName<>'CommonLink' and obj.parentId="+modulesId+condition+" and objUR.userId="
					+ user.getUserId()
					+ " and objUR.roleId=objRPM.roleId and objRPM.moduleId=obj.id and obj.isMenu=1 order by obj.moduleLevel asc";
			}
			list = bpo.search(sql);
			
			if(list == null || list.size()==0){
				list.add(bpo.findByPk(Long.parseLong(modulesId)));
				/*
				List searchList = bpo.search("from DataDictionary where parentId="+modulesId);
				if(isGlobalPermissions(moduleName)){
					DataDictionary dd = new DataDictionary();
					dd.setParentId(Long.parseLong(modulesId));
					dd.setText("报送单位");
					dd.setValue("sentDep");
					searchList.add(dd);
				}
				this.setFormValue("", searchList);*/
			}
			
			for(int i=0;list!=null&&i<list.size();i++){
				SysModules obj = (SysModules)list.get(i);
				obj.setModuleCname(obj.getModuleCname().replaceAll("\\s", ""));
			}
		}
		this.setFormValue("selData", list);
		return ActionType.ACTION_CHANGE;
	}
	
	
}
